
#include "CobwebSqlite.h"
#include "Debug.h"
#include <sstream>
using namespace std;

CobWebSqlite:: CobWebSqlite(const char *name, int max)
{
  m_dbName = name;
  db = NULL;
  MAXT = max;
}

CobWebSqlite:: ~CobWebSqlite()
{
	if(db != NULL)
		sqlite3_close(db);
	db = NULL;
}

bool CobWebSqlite :: Initialize()
{
	if(db == NULL)
	{
		try {
			char *zErrMsg = 0;
			int rc;
			rc = sqlite3_open( m_dbName.c_str(), &db);
			if( rc ){
				fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
				sqlite3_close(db);
				return false;
			}
			for(int i=0; i< MAXT; i++)
			{
				ostringstream  sql;
				sql << "create table sns"<< i << "(nid integer, name test,friends test, primary key(nid))";
				rc = sqlite3_exec(db, sql.str().c_str(), NULL, 0, &zErrMsg);
				if( rc != SQLITE_OK ){
					fprintf(stderr, "SQL error: %s\n", zErrMsg);
					sqlite3_free(zErrMsg);
				}
			}
		}
		catch (...) {
			cerr << "cobweb Initialize ERROR " <<  "\n";
			return false;
		}
	}
	return true;
}

bool CobWebSqlite :: Save(char *key, char *name, char *val, long expire )
{
	ostringstream sql;
        int nid = atoi(key);
        char *zErrMsg = 0;
	sql <<"INSERT INTO sns"<<(nid%MAXT) <<" VALUES("<<  atoi(key) <<", '"<<name<<"','"<<val<<"',"<< expire<< " )";
	try{
		int rc = sqlite3_exec(db, sql.str().c_str(), NULL, 0, &zErrMsg);
		if( rc != SQLITE_OK ){
			fprintf(stderr, "SQL error: %s\n", zErrMsg);
			sqlite3_free(zErrMsg);
                        return false;
		}	
                else
                   return true;
	}catch(...)
	{
		return false;
	}
}

bool CobWebSqlite :: Replace(char *key, char *name ,char *val, long expire )
{
	ostringstream sql;
        int nid = atoi(key);
        char *zErrMsg = 0;
	sql <<"UPDATE sns"<<(nid%MAXT)<<" SET name='"<<name<<", friends='"<< val<<"', expire="<<expire <<" WHERE nid="<<nid;
	try{
		int rc = sqlite3_exec(db, sql.str().c_str(), NULL, 0, &zErrMsg);
		if( rc != SQLITE_OK ){
			fprintf(stderr, "SQL error: %s\n", zErrMsg);
			sqlite3_free(zErrMsg);
			return false;
		}	
		else
			return true;
	}catch(...)
	{
		return false;
	}
}

bool CobWebSqlite :: Fetch(char *key,  string &name, string &val, long &expire )
{
	const char *zErrMsg = 0;
	try{		// Acquire a cursor for the table.
		int nid = atoi(key);
                ostringstream sql;
		sql << "SELECT name, friends, expire FROM sns"<<(nid%MAXT) <<" WHERE nid="<<nid;
		sqlite3_stmt *stmt;
	 	int rc = sqlite3_prepare(db, sql.str().c_str(), sql.str().length() ,&stmt, &zErrMsg);
		rc = sqlite3_step(stmt);
                bool ret = false;
		if(rc == SQLITE_ROW)
		{
			name.append((char *)sqlite3_column_text(stmt,0));
			val =(char *)sqlite3_column_text(stmt, 1);
			expire = sqlite3_column_double(stmt, 2);
                        ret = true;
		}
		sqlite3_finalize(stmt);
                return ret; 
	}
	catch (...) {
                return false;
	}
}
